require('express-async-errors');
const express = require('express');
const app = express();
const PORT = 8080;
const connectDB = require('./utils/connectDB');
const { NotFoundError } = require('./errors');
require('dotenv').config();
app.use(express.json());

// 全局响应中间件
const resMiddleWare = require('./utils/res-handler');
app.use(resMiddleWare);

// 注册路由
const mountRoutes = require('./routes/index');
mountRoutes(app);

// 匹配其他未定义
app.all('*', () => {
   throw new NotFoundError('Route does not exist');
});

// 全局错误捕获
const errorMiddleware = require('./utils/error-handler');
app.use(errorMiddleware);

const start = async () => {
   try {
      await connectDB(process.env.MONGO_URI);
      app.listen(PORT, console.log(`Server is running on port ${PORT}`));
   } catch (error) {
      console.log(error);
   }
};

start();
